<template>
  <div class="map">
    <el-form
      :model="form"
      ref="ruleForm"
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-row>
        <el-col :span="15">
          <el-form-item label="地址" style="position: relative; display: flex">
            <el-select
              v-model="address"
              @change="selectOneAddr"
              :remote-method="searchWithName"
              style="width: 80%"
              filterable
              remote
              placeholder="请输入关键词搜索"
            >
              <el-option
                v-for="(item, inx) in addressList"
                :key="inx"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label="经纬度">
            <span>{{ longitudeFormValue }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div id="container" style="width: 100%; height: 525px"></div>
  </div>
</template>

<script>
export default {
  props: {
    lat: {
      // type: Number,
      default: 0,
    },
    lng: {
      // type: Number,
      default: 0,
    },
  },
  data() {
    return {
      address: "",
      marker: null,
      addressList: [],
      placeSearch: "",
      form: {
        // 经度
        longitude: 0,
        // 纬度
        latitude: 0,
      },
    };
  },
  mounted() {
    this.form.longitude = this.lng;
    this.form.latitude = this.lat;

    this.initMap();
  },
  watch: {
    lng: {
      handler(val) {
        if (val) {
          this.initMap();
        }
      },
    },
  },
  computed: {
    longitudeFormValue() {
      if (this.form.longitude && this.form.latitude) {
        return this.form.longitude + "," + this.form.latitude;
      } else {
        return "";
      }
    },
  },
  destroyed() {
    if (this.marker) {
      // this.marker.setMap(null);
    }
  },
  beforeDestroy() {
    if (this.marker) {
      this.marker.setMap(null);
    }
  },
  methods: {
    destroyMap() {
      if (this.marker) {
        this.marker.setMap(null);
      }
    },
    initMap() {
      let _this = this;
      if (this.lat && this.lng) {
        const mapObj = {
          resizeEnable: true,
          zoom: 16,
          center: [this.lng, this.lat],
        };
        _this.map = new AMap.Map("container", mapObj);
        this.marker = new AMap.Marker({
          icon: new AMap.Icon({
            image:
              "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            size: new AMap.Size(22, 28), //图标所处区域大小
            imageSize: new AMap.Size(22, 28), //图标大小
          }),
          position: [this.lng, this.lat],
          offset: new AMap.Pixel(-13, -20),
        });
        this.marker.setMap(_this.map);
      } else {
        _this.map = new AMap.Map(document.getElementById("mapDiv"), {
          resizeEnable: true,
          center: [this.lng, this.lat],
          zoom: 16,
        });
      }

      // 设置经纬度转为地址范围
      this.geocoder = new AMap.Geocoder({
        city: "320117", //城市设为北京，默认：“全国”
        radius: 3000, //范围，默认：500
      });
      AMap.plugin(["AMap.PlaceSearch"], function () {
        //构造地点查询类
        _this.placeSearch = new AMap.PlaceSearch({
          // type: '餐饮服务', // 兴趣点类别
          pageSize: 10, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: "320117", // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          map: _this.map, // 展现结果的地图实例
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
      });

      this.map.on("click", this.onMapClick);
    },

    onMapClick(e) {
      this.form.longitude = e.lnglat.lng;
      this.form.latitude = e.lnglat.lat;

      if (this.marker) {
        this.map.remove(this.marker);
        this.marker = null;
      }
      this.marker = new AMap.Marker({
        icon: new AMap.Icon({
          image:
            "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          size: new AMap.Size(22, 28), //图标所处区域大小
          imageSize: new AMap.Size(22, 28), //图标大小
        }),
        position: [e.lnglat.lng, e.lnglat.lat],
        offset: new AMap.Pixel(-13, -20),
      });
      this.marker.setMap(this.map);

      this.regeoCode(e.lnglat);
    },
    regeoCode(_lnglat) {
      let _this = this;
      _this.map.clearMap();
      _this.geocoder.getAddress(_lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          _this.address = result.regeocode.formattedAddress;
          var marker = new AMap.Marker({
            map: _this.map,
            position: _lnglat,
          });
          _this.infoWindow.setContent(
            _this.createContent({
              name: _this.address,
            })
          );
          _this.map.setCenter(marker.getPosition());
          _this.infoWindow.open(_this.map, marker.getPosition());
          this.form.latitude = _lnglat.lat;
          this.form.longitude = _lnglat.lng;
        } else {
          _this.$message.warning("根据经纬度查询地址失败");
        }
      });
    },

    searchWithName(query) {
      let _this = this;
      if (query) {
        _this.placeSearch.search(query, (complete, res) => {
          _this.addressList = res.poiList.pois;
        });
      } else {
        _this.addressList = [];
      }
    },

    selectOneAddr(val) {
      let _obj = this.addressList.find((_v) => _v.name == val);
      if (_obj.id) {
        if (this.marker) {
          this.map.remove(this.marker);
          this.marker = null;
        }
        //添加marker
        this.marker = new AMap.Marker({
          map: this.map,
          position: _obj.location,
        });
        this.form.latitude = _obj.location.lat;
        this.form.longitude = _obj.location.lng;
        this.address = _obj.name;
        this.map.setCenter(this.marker.getPosition());
        this.infoWindow.setContent(this.createContent(_obj));
        this.infoWindow.open(this.map, this.marker.getPosition());
      } else {
        this.$message.warning("定位出错请重新选择");
      }
    },
  },
};
</script>

<style lang="scss">
.map {
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>